﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using Chat_WebClient.Models;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Net.Http.Formatting;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Chat_WebClient.Controllers
{
    public class HomeController : Controller
    {
        private const String ServerURL = "http://localhost:53220";
        private static OpenIdRelyingParty openid = new OpenIdRelyingParty();
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult GoogleMap()
        {
            return View();
        }

        [ValidateInput(false)]
        public ActionResult Authenticate(string ReturnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                //Let us submit the request to OpenID provider
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(
                                             Request.Form["openid_identifier"]);
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        request.AddExtension(fetch);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewBag.Message = ex.Message;
                        return View("LogOn");
                    }
                }

                ViewBag.Message = "Invalid identifier";
                return View("Index");
            }

            //Let us check the response
            switch (response.Status)
            {

                case AuthenticationStatus.Authenticated:
                    var fetch = response.GetExtension<FetchResponse>();
                    string email = string.Empty;
                    if (fetch != null)
                    {
                        email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                    }

                    LoginModel lm = new LoginModel();
                    String OpenID = response.ClaimedIdentifier;
                    // check if user exist
                    LoginModel user = GetUser(OpenID, email);
                    if (user != null)
                    {
                        lm.UserName = user.UserName;
                        lm.Email = user.Email;
                        lm.OpenID = user.OpenID;
                    }
                    else ViewBag.Message = "Cannot verify openid Account";
                    return View("Index", lm);

                case AuthenticationStatus.Canceled:
                    ViewBag.Message = "Canceled at provider";
                    return View("Index");
                case AuthenticationStatus.Failed:
                    ViewBag.Message = response.Exception.Message;
                    return View("Index");
            }

            return new EmptyResult();

        }

        private LoginModel GetUser(string id, string email)
        {
            String requesturl = ServerURL + "/api/Account?ClaimID={0}&Email={1}";
            HttpWebRequest request = HttpWebRequest.Create(String.Format(requesturl, HttpUtility.UrlEncode(id), HttpUtility.UrlEncode(email))) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";
            LoginModel user = null;
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        String str = reader.ReadToEnd();
                        JObject o = JObject.Parse(str);
                        user = new LoginModel();
                        user.UserName = o["Username"].ToString();
                        user.OpenID = HttpUtility.UrlEncode(o["OpenID"].ToString());
                        return user;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return user;
        }

        [HttpPost]
        public ActionResult UploadAvartar(Avarta avartar)
        {
            // Create the JSON formatter.
            HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;
            if (file.ContentLength > 0)
            {

                MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
                // Use the JSON formatter to create the content of the request body.
                byte[] buf;  // byte array
                Stream stream = file.InputStream;  //initialise new stream
                buf = new byte[stream.Length];  //declare arraysize
                stream.Read(buf, 0, buf.Length); // read from stream to byte array
                HttpContent content = new ObjectContent<byte[]>(buf, jsonFormatter);

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:53220/");
                client.DefaultRequestHeaders.Accept.Add(
                  new MediaTypeWithQualityHeaderValue("application/json"));

                // Send the request.
                var resp = client.PostAsync("api/Avatar/" + avartar.UserNameUpload, content).Result;
                if (resp.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }
            }
            return RedirectToAction("Index");
        }
    }
}

